package ssq.gamest.webserver;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;

import ssq.utils.FileUtils;
import ssq.utils.LogUtils;
import ssq.utils.SqliteAccesser;

public class LoginHandler extends HandlerUtils
{
    private SqliteAccesser sqliteAccesser;
    public final int       wsport;

    public LoginHandler(int wsport)
    {
        this.wsport = wsport;
        sqliteAccesser = new SqliteAccesser("user_info")
        {

            @Override
            public String getVersion()
            {
                return "1.0";
            }
            
            @Override
            public void updateDB()
            {

            }

            @Override
            public void tryInitializeDB()
            {
                super.tryInitializeDB();
                
                try
                {
                    update(FileUtils.openAssetsString("sql/create.sql"), null);
                }
                catch (Exception e)
                {
                }
            }
        };

        sqliteAccesser.checkDatabase();
        errorCode = new String[] { "ok", "用户名已存在!", "密码太短!", "数据不合法!", "用户不存在!", "密码错误", "未知操作" };
    }

    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException
    {
        List<String> l = new ArrayList<String>();
        if (parse(request, l).size() == 0)
        {
            return;
        }

        String path = l.get(1), query = l.get(2);

        int code;
        String result;

        if (path.startsWith("/c"))
        {
            code = checkDuplicate(query);
        }
        else
        {
            JSONObject jo = JSONObject.fromObject(query);
            String name = jo.getString("name"), pass = jo.getString("pass");
            if (path.startsWith("/s"))
            {
                if (pass.length() < 6)
                {
                    code = 2;
                }
                else
                {
                    code = checkDuplicate(name);

                    String gender = jo.getString("gender");

                    if (code == 0)
                    {
                        try
                        {
                            signup(name, pass, gender);
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            code = 3;
                        }
                    }
                }
            }
            else if (path.startsWith("/l"))
            {
                if (checkDuplicate(name) == 0)
                {
                    code = 4;
                }
                else
                {
                    code = checkPass(name, pass);
                }
            }
            else
            {
                code = 6;
            }
        }

        result = errorCode[code];
        if (code == 0 && path.startsWith("/l"))
        {
            result += wsport;
        }

        response.setStatusCode(HttpStatus.SC_OK);

        StringEntity body = new StringEntity(result, "UTF-8");

        response.setEntity(body);
        LogUtils.logString(result, path, true);
    }

    private int checkPass(String name, String pass)
    {
        int result;
        try
        {
            ResultSet results = sqliteAccesser.query("select pid from players where name=? and pass=?", new String[] { name, pass });
            if (results.next())
            {
                result = 0;
            }
            else
            {
                result = 5;
            }
            results.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            result = 3;
        }
        return result;
    }

    protected void signup(String name, String pass, String gender) throws Exception
    {
        sqliteAccesser.update("insert into players (name, pass, registerTime, gender, played, winned, tied, money, experience) values (?, ?, ?, ?, ?, ?, ?, ?, ?)", new Object[] { name, pass, new Date().getTime(), gender, 0, 0, 0, 0, 0 });
    }

    protected int checkDuplicate(String name)
    {
        int result;
        try
        {
            ResultSet results = sqliteAccesser.query("select pid from players where name=?", new Object[] { name });
            if (results.next())
            {
                result = 1;
            }
            else
            {
                result = 0;
            }
            results.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            result = 3;
        }
        return result;
    }
}
